package top.zerocn.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Properties;

import top.zerocn.entity.User;

public class UserOperator {
	private static Properties properties = new Properties();

	public boolean saveUser(User user) {
		properties.setProperty("id", user.getId());
		properties.setProperty("name", user.getName());
		properties.setProperty("password", user.getPassword());
		properties.setProperty("sex", user.getSex());
		properties.setProperty("balance", user.getBalance().toPlainString());

		String path = System.getProperty("user.dir") + "/src/top/zerocn/dao/" + user.getId() + ".properties";
//		String path = this.getClass().getResource("").getPath().replace("%20", " ") + user.getId() + ".properties";
		try (FileOutputStream fileOutputStream = new FileOutputStream(new File(path))) {
			properties.store(fileOutputStream, null);
			return ResourceOperator.saveFile(user.getId());
		} catch (IOException e) {
			System.err.println("写入" + user.getId() + ".properties文件出错\n" + e.getMessage());
			return false;
		}

	}

	public User getUser(String id) {
		File file = ResourceOperator.getFile(id);
		if (Objects.isNull(file)) {
			return null;
		}

		try (FileInputStream fileInputStream = new FileInputStream(file)) {
			properties.load(fileInputStream);
		} catch (IOException e) {
			System.err.println("读取" + id + ".properties文件出错\n" + e.getMessage());
		}

		if (properties.isEmpty()) {
			return null;
		}

		return new User(properties.getProperty("id"), properties.getProperty("name"),
				properties.getProperty("password"), properties.getProperty("sex"),
				new BigDecimal(properties.getProperty("balance")));
	}
}
